"use server"

import { cookies } from "next/headers"

const API_URL = 'http://127.0.0.1:8000'

// 认证函数的类型定义
interface LoginCredentials {
  account_id: string // 改为使用学号登录
  password: string
}

interface RegistrationData {
  name: string
  email?: string
  password: string
  role: "student" | "counselor" | "admin"
  account_id: string  // account_id
  phoneNumber: string
  academy?: string // 辅导员部门或学生学院
  major?: string      // 学生专业
  class_?: string      // 学生班级
}

interface AuthResult {
  success: boolean;
  message?: string | Array<{type?: string, loc?: string[], msg?: string, input?: any}> | {msg?: string, [key: string]: any};
  userId?: string;
}

// 辅助函数：验证学号格式
const isValidAccount_id = (account_id: string): boolean => {
  // 简单验证：学号应为字母数字组合且至少8位
  return /^[A-Za-z0-9]{8,}$/.test(account_id)
}

// 辅助函数：验证手机号格式
const isValidPhoneNumber = (phoneNumber: string): boolean => {
  // 简单验证：11位数字
  return /^\d{11}$/.test(phoneNumber.replace(/[^0-9]/g, ""))
}

// 辅助函数：验证邮箱格式
const isValidEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 登录函数
export async function loginUser(credentials: LoginCredentials): Promise<AuthResult> {
  try {
    const response = await fetch(`${API_URL}/api/v1/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        account_id: credentials.account_id, // 与后端字段对齐
        password: credentials.password
      }),
      cache: 'no-store'
    });

    const data = await response.json();

    if (!response.ok) {
      return { success: false, message: data.detail || "登录失败" };
    }

    return { success: true, userId: data.user_id.toString() };
  } catch (error) {
    console.error("登录请求失败:", error);
    return { success: false, message: "网络错误，请稍后再试" };
  }
}

// 注册函数
export async function registerUser(data: RegistrationData): Promise<AuthResult> {
  try {
    // 验证必填字段和格式（保留现有验证）
    if (!data.name || !data.password || !data.phoneNumber) {
      return { success: false, message: "必填字段不能为空" }
    }

    // 验证角色特定字段
    if (data.role === "student" && !data.account_id) {
      return { success: false, message: "学生注册必须提供学号" }
    }

    // 验证学号格式（如果提供）
    if (data.account_id && !isValidAccount_id(data.account_id)) {
      return { success: false, message: "学号格式不正确" }
    }

    // 验证手机号
    if (!isValidPhoneNumber(data.phoneNumber)) {
      return { success: false, message: "手机号格式不正确" }
    }

    // 验证邮箱（如果提供）
    if (data.email && !isValidEmail(data.email)) {
      return { success: false, message: "邮箱格式不正确" }
    }

    // 验证密码强度
    if (data.password.length < 8) {
      return { success: false, message: "密码长度必须至少为8个字符" }
    }
    // 调整请求体以匹配后端API预期格式
    const userData = {
      name: data.name,
      email: data.email || "",
      account_id: data.account_id,
      password: data.password,
      phone_number: data.phoneNumber,
      role: data.role,
    };

// 根据角色设置请求体
    let requestBody;
    if (data.role === "student") {
      requestBody = {
        user_data: userData,
        student_data: {
          academy: data.academy || "",
          major: data.major || "",
          class_: data.class_ || ""
        }
      };
    } else if (data.role === "counselor") {
      requestBody = {
        user_data: userData,
        counselor_data: {
          department: data.academy || "",
          office_location: data.major || "" // 可以使用major字段作为office_location
        }
      };
    }

    const response = await fetch(`${API_URL}/api/v1/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestBody),
      cache: 'no-store'
    });

    if (!response.ok) {
      const errorText = await response.text();
      try {
        // 尝试解析为 JSON
        const errorData = JSON.parse(errorText);
        // 特殊处理 FastAPI 验证错误
        if (Array.isArray(errorData)) {
          return { success: false, message: errorData };
        }
        return { success: false, message: errorData.detail || "注册失败" };
      } catch (e) {
        // 文本不是 JSON
        return { success: false, message: errorText || `注册失败: ${response.status}` };
      }
    }
    // 如果请求成功
    const responseData = await response.json();
    // 防止user_id不存在导致的错误
    return { 
      success: true, 
      userId: responseData.user_id ? responseData.user_id.toString() : undefined 
    };
  } catch (error) {
    console.error("注册请求失败:", error);
    // 添加更详细的错误日志
    if (error instanceof Error) {
      console.error("错误详情:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    return { success: false, message: "网络错误，请稍后再试" };
  }
}

export async function logoutUser(): Promise<AuthResult> {
  try {
    // 可选：通知后端登出
    await fetch(`${API_URL}/api/v1/auth/logout`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${(await cookies()).get('auth_token')?.value}`
      },
      cache: 'no-store'
    });

    // 清除认证cookie
    (await cookies()).delete("auth_token");

    return { success: true };
  } catch (error) {
    console.error("登出请求失败:", error);
    // 即使API请求失败，也清除本地cookie
    (await cookies()).delete("auth_token");
    return { success: true };
  }
}
